<template>
  <div class="pagebody">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 新闻发布 </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button type="primary"
                   icon="el-icon-search"
                   @click="handleSearch">搜索</el-button>
        <el-button type="primary"
                   icon="el-icon-plus"
                   @click="handleAddNew">添加新闻</el-button>
      </div>
      <el-table :data="tableData"
                v-loading="tableLoading"
                border
                class="table"
                ref="mainTable">
        <el-table-column prop="type"
                         label="类型"
                         :formatter="
                        (r, c, v, i) => {
                            return typeDict[v] ? typeDict[v].name : '暂无';
                        }
                    "
                         align="center"></el-table-column>
        <el-table-column prop="title"
                         show-overflow-tooltip
                         label="主标题"
                         align="center"></el-table-column>
        <el-table-column prop="vicetitle"
                         show-overflow-tooltip
                         label="副标题"
                         align="center"></el-table-column>
        <el-table-column label="是否首页展示"
                         align="center">
          <template slot-scope="scope">
            {{ scope.row.isshow ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column prop="imageid"
                         width="200"
                         label="图片"
                         align="center">
          <template slot-scope="scope">
            <el-image v-if="scope.row.imageid"
                      class="UserCheckImage"
                      :src="baseFileURL + scope.row.imageid"
                      fit="contain"
                      :preview-src-list="previewSrcList"></el-image>
            <div v-else>暂无图片</div>
          </template>
        </el-table-column>
        <el-table-column prop="addtime"
                         label="添加时间"
                         align="center"></el-table-column>
        <el-table-column label="操作"
                         width="200"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       icon="el-icon-s-order"
                       @click="handleDetail(scope.$index, scope.row)">详情</el-button>
            <el-button type="text"
                       icon="el-icon-edit"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text"
                       icon="el-icon-delete"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background
                       layout="sizes, total, prev, pager, next"
                       :current-page="query.index"
                       :page-sizes="[10, 20, 30, 40, 50, 100]"
                       :page-size="query.pageSize"
                       :total="itemTotal"
                       @current-change="handlePageChange"
                       @size-change="handlePageSizeChange"></el-pagination>
      </div>
    </div>

    <el-dialog :title="form.menutype == '1' ? '发布新闻' :'编辑新闻' "
               fullscreen
               center
               v-if="editVisible"
               :visible.sync="editVisible">
      <div class="FlexRowLineVCenter">
        <div class="FlexFit">
          <div class="FlexCenter FormContent">
            <div>
              <div>新闻图片</div>
              <customUpload accept="image/*"
                            ref="UploadImage"
                            :limit="1"
                            listType="picture"
                            tip="只能上传jpg/png文件"
                            :fileList="form.initImage"
                            v-on:update:idlist="UpdateImageList">
              </customUpload>
            </div>
            <div class="FlexFit">
              <el-form ref="form"
                       size="mini"
                       :model="form"
                       :rules="formRules"
                       label-width="120px">
                <el-form-item label="新闻主标题"
                              prop="title">
                  <el-input v-model="form.title"
                            maxlength="100"
                            show-word-limit
                            placeholder="请填写新闻主标题"
                            clearable
                            class="formInput"></el-input>
                </el-form-item>
                <el-form-item label="新闻副标题"
                              prop="vicetitle">
                  <el-input v-model="form.vicetitle"
                            maxlength="100"
                            show-word-limit
                            placeholder="请填写新闻副标题"
                            clearable
                            class="formInput"></el-input>
                </el-form-item>
                <el-form-item label="发布类型"
                              prop="type">
                  <el-select v-model="form.source"
                             class="formInput"
                             placeholder="请选择发布类型">
                    <el-option v-for="item in sourceDict"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="新闻类型"
                              prop="type">
                  <el-select v-model="form.type"
                             class="formInput"
                             placeholder="请选择新闻类型">
                    <el-option v-for="item in typeDict"
                               :key="item.id"
                               :label="item.name"
                               :value="item.id"> </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="状态"
                              prop="showtype">
                  <el-checkbox v-model="form.isshow">是否首页展示</el-checkbox>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div>新闻内容</div>
          <div id="PreviewNews">
            <template v-if="form.source == 0">

              <tinymceEditor v-model="formExtra.editor" />
            </template>
            <template v-else-if="form.source == 1">
              <el-input v-model="formExtra.webUrl"
                        maxlength="100"
                        show-word-limit
                        placeholder="请填写新闻链接"
                        clearable
                        class="formInput"></el-input>
            </template>
            <template v-else-if="form.source == 2">
              <customUpload accept="video/*"
                            ref="UploadContentImage"
                            :limit="1"
                            listType="video"
                            tip="只能上传视频文件"
                            :fileList="formExtra.initVideo"
                            :onPreview="previewVideo"
                            v-on:update:idlist="UpdateContentList">
              </customUpload>
            </template>
          </div>
        </div>
        <div style="margin: 0 20px"
             v-if="form.source == 0">
          <div class="PreviewTitle">移动端预览</div>
          <div class="PreviewDiv"
               v-html="formExtra.editor"></div>
        </div>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button type="primary"
                   @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <detailDialog :visible.sync="detailVisible"
                  :data="detailInfo"
                  :dialogDrag="false"
                  direction="row"
                  width="80%"
                  :dataType="detailType">
      <template slot="content"
                v-if="detailInfo.source == 0">
        <el-descriptions-item label="移动端预览"
                              :span="1">
          <div style="margin: 0 20px">
            <div class="PreviewDiv"
                 id="PreviewNews2"
                 v-html="detailInfo.content"></div>
          </div>
        </el-descriptions-item>
      </template>
      <template slot="urlcontent"
                v-if="detailInfo.source == 1">
        <el-descriptions-item label="网页连接"
                              :span="1">
          <a :href="detailInfo.content"
             target="view_window">{{detailInfo.content}}</a>
        </el-descriptions-item>
      </template>
      <template slot="videocontent"
                v-if="detailInfo.source == 2">
        <el-descriptions-item label="视频连接"
                              :span="1">
          <a :href="detailInfo.content"
             target="view_window">{{detailInfo.content}}</a>
        </el-descriptions-item>
      </template>
    </detailDialog>
  </div>
</template>

<script>
import API from '../../../api/index'; //读入restfulAPI
import StringTool from '../../../utils/StringTool';
import request from '../../../utils/request';
import dataTable from './dataTable';
import detailDialog from '../../common/dialog/detailDialog.vue';
import { Base64 } from 'js-base64';
import customUpload from '../../common/upload/customUpload.vue';
import tinymceEditor from '../../common/editor/tinymceEditor.vue';
import JSTool from '../../../utils/JSTool';
import MainTool from '../../../utils/MainTool';
let defaultForm = {
  menutype: 1,
  title: '',
  vicetitle: '',
  source: 0,
  type: '',
  isshow: false,
  imageid: '',
  initImage: [],
};
let defaultFormExtra = {
  webUrl: "",
  editor: "",
  initVideo: [],
  videoUrlId: null,
};
export default {
  name: 'newsTable',
  mixins: [dataTable],
  components: {
    detailDialog,
    customUpload,
    tinymceEditor
  },
  data () {
    return {
      searchSet: {},
      editVisible: false,
      typeDict: {
        1: { id: 1, name: '系统公告' },
        2: { id: 2, name: '发货须知' },
        3: { id: 3, name: '新手手册' },
        4: { id: 4, name: '业内新闻' },
        5: { id: 5, name: '优惠信息' },
        6: { id: 6, name: '发货协议' },
      },
      sourceDict: {
        0: { id: 0, name: '自定义编辑' },
        1: { id: 1, name: '网页链接' },
        2: { id: 2, name: '上传视频' }
      },
      form: {},
      formExtra: {},
      formRules: {
        title: [
          { required: true, message: '参数不能为空', trigger: 'blur' },
          { max: 100, message: '长度最大为100个字符', trigger: 'blur' }
        ],
        vicetitle: [
          { required: true, message: '参数不能为空', trigger: 'blur' },
          { max: 100, message: '长度最大为100个字符', trigger: 'blur' }
        ],
        type: [{ required: true, message: '参数不能为空', trigger: 'blur' }]
      },
      detailVisible: false,
      detailInfo: {},
      detailType: [
        {
          style: { 'flex': 1 },
          attrs: { column: 1, direction: "vertical", },
          list: [
            { label: '新闻主标题', key: 'title', },
            { label: '新闻副标题', key: 'vicetitle', },
            { label: '发布类型', key: 'source', format: (r, v) => { return this.sourceDict[v] ? this.sourceDict[v].name : "未知"; } },
            { label: '新闻类型', key: 'type', format: (r, v) => { return this.typeDict[v] ? this.typeDict[v].name : "未知"; } },
            { label: '是否首页显示', key: 'isshow', format: (r, v) => { return v ? "是" : "否" } },
            { label: '新闻图片', key: 'images', type: 'image' },
            { key: 'videocontent', type: 'slot', },
            { key: 'urlcontent', type: 'slot', },
          ]
        },
        {
          attrs: { column: 1, direction: "vertical" },
          list: [

            { key: 'content', type: 'slot', }
          ]
        }
      ],
    };
  },
  created () {
    this.init();
  },
  mounted () { },
  computed: {
    baseFileURL: function () {
      return this.$store.state.baseURL + 'api/File?id=';
    },
    previewSrcList: function () {
      let list = [];
      this.tableData.map((it) => {
        if (it.imageid) {
          list.push(this.baseFileURL + it.imageid);
        }
      });
      // `this` 指向 vm 实例
      return list;
    }
  },
  methods: {
    //页面初始化
    init () {
      this.getData();
    },
    getData () {
      this.tableLoading = true;
      API.StandardDoWith(API.Appnew.Get(this.getQuery()), this, {
        success: (detail) => {
          this.itemTotal = detail.count;
          this.tableData = detail.list;
        },
        complete: () => {
          this.tableLoading = false;
        }
      });
    },
    handleAddNew () {
      this.editVisible = true;
      this.form = Object.assign({}, defaultForm)
      this.formExtra = Object.assign({}, defaultFormExtra)
    },
    UpdateImageList (idlist) {
      if (idlist.length) {
        this.form.imageid = idlist[0];
      } else {
        this.form.imageid = null
      }
    },
    UpdateContentList (idlist) {
      if (idlist.length) {
        this.formExtra.videoUrlId = idlist[0];
      } else {
        this.formExtra.videoUrlId = null
      }
    },

    saveEdit () {
      // if (!this.form.content) {
      //     this.$message.error(`新闻内容不能为空`);
      //     return;
      // }
      this.$refs.form.validate((valid) => {
        if (valid) {
          let requestform = Object.assign({}, this.form);
          if (this.form.source == 0) {
            requestform.content = Base64.encode(this.formExtra.editor);
          } else if (this.form.source == 1) {
            requestform.content = Base64.encode(this.formExtra.webUrl);
          } else if (this.form.source == 2) {
            requestform.contentimageid = this.formExtra.videoUrlId;
          }

          if (this.form.menutype == '1') {
            this.requestAddNew(requestform);
          } else {
            this.requestEditNew(requestform);
          }
        } else {
          this.$message.error(`表单验证失败，无法提交`);
          return false;
        }
      });
    },
    cancelEdit () {
      this.editVisible = false
      this.form = Object.assign({}, defaultForm)
      this.formExtra = Object.assign({}, defaultFormExtra)
    },
    requestAddNew (data) {
      API.StandardDoWith(API.Appnew.Post(data), this, {
        loading: '添加新闻中',
        success: (detail) => {
          this.editVisible = false;
          this.$message.success(`添加新闻成功`);
          this.getData();
        }
      });
    },
    requestEditNew (data) {
      API.StandardDoWith(API.Appnew.Put(data), this, {
        loading: '编辑新闻中',
        success: (detail) => {
          this.editVisible = false;
          this.$message.success(`编辑新闻成功`);
          this.getData();
        }
      });
    },
    handleDelete (index, row) {
      // 二次确认删除
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          API.StandardDoWith(API.Appnew.Delete({ id: row.id }), this, {
            success: (detail) => {
              this.$message.success(`成功删除新闻`);
              this.getData();
            }
          });
        })
        .catch(() => { });
    },
    handleEdit (index, row) {
      let obj = JSTool.DeepClone(row);
      obj.menutype = 2;
      // obj.imageurl = MainTool.FileIdToUrl(obj.imageid);
      obj.initImage = [{ name: '首页图.jpg', url: MainTool.FileIdToUrl(obj.imageid), response: { detail: { id: obj.imageid } } }]
      this.form = obj
      this.formExtra = Object.assign({}, defaultFormExtra)
      this.editVisible = true;

      // this.formExtra.initVideo = [{ name: '新闻内容', url: "https://api.darenexpress.com/api/File?id=1493108714796879872", response: { detail: { id: 1493108714796879872 } } }];
      this.$nextTick(() => {
        API.StandardDoWith(API.Appnewcontent.Get({ id: row.id }), this, {
          loading: {
            target: "#PreviewNews",
          },
          success: (detail) => {
            if (detail.source == 0) {
              this.formExtra.editor = Base64.decode(detail.content);
            } else if (detail.source == 1) {
              let content = Base64.decode(detail.content);
              console.log(content)
              if (content.startsWith("<script>window.location='")) content = content.replace("<script>window.location='", "")
              if (content.endsWith("';<\/script>")) content = content.replace("';<\/script>", "")
              this.formExtra.webUrl = content;

            } else {
              this.formExtra.videoUrlId = detail.urlid;
              this.formExtra.initVideo = [{ name: '新闻内容', url: MainTool.FileIdToUrl(detail.urlid), response: { detail: { id: detail.urlid } } }];
              console.log(this.formExtra.initVideo)
            }
          }
        });
      })
    },
    handleDetail (index, row) {
      this.detailVisible = true;

      let obj = JSTool.DeepClone(row);
      obj.image = MainTool.FileIdToUrl(obj.imageid);
      this.detailInfo = obj;
      this.$nextTick(() => {
        API.StandardDoWith(API.Appnewcontent.Get({ id: row.id }), this, {
          loading: {
            target: "#PreviewNews2",
          },
          success: (detail) => {
            let obj = Object.assign({}, this.detailInfo)
            if (obj.source == 0) {
              obj.content = Base64.decode(detail.content);
            } else if (detail.source == 1) {
              let content = Base64.decode(detail.content);
              if (content.startsWith("<script>window.location='")) content = content.replace("<script>window.location='", "")
              if (content.endsWith("';<\/script>")) content = content.replace("';<\/script>", "")
              obj.content = content
            } else {
              obj.content = MainTool.FileIdToUrl(detail.urlid)
            }
            this.detailInfo = obj
          }
        });
      })

    },
    previewVideo (file) {
      window.open(file.url, "新闻内容",)
    }
  }
};
</script>

<style scoped>
@import '../../../assets/css/dataTable.css';
.UserCheckImage {
    max-height: 100px;
    max-width: 100px;
    width: 100%;
}
.FormContent {
    margin-bottom: 20px;
}
.PreviewDiv {
    width: 350px;
    height: 730px;
    border: gray 2px solid;

    overflow-x: hidden;
    overflow-y: scroll;
}
.PreviewTitle {
    font-size: 1.5em;
    font-weight: bold;
}
</style>
